<template>
  <div class="dataTarget">
    <el-dialog
      title="浏览文件"
      :visible.sync="dialogTableVisible"
      @close="handleCloseDialog"
    >
      <div>
        <el-button type="text" disabled
          >当前路径:{{ dataTarget.fileUrl }}</el-button
        >
        <el-button
          @click="handlePrevious"
          type="primary"
          size="mini"
          icon="el-icon-arrow-left"
          >返回上一级</el-button
        >
        <el-button @click="handleconfirm" type="primary" size="mini"
          >选择</el-button
        >
      </div>
      <el-scrollbar style="height: 100%">
        <el-tree
          :data="gridData"
          :props="defaultProps"
          :default-expand-all="true"
          @node-click="handleNodeClick"
        >
          <span class="custom-tree-node" slot-scope="{ node }">
            <span>
              <i
                :class="
                  node.data.type === 2
                    ? 'el-icon-folder-opened'
                    : 'el-icon-s-order'
                "
              ></i>
              {{ node.label }}
            </span>
          </span>
        </el-tree>
      </el-scrollbar>
    </el-dialog>
    <el-divider content-position="left"> <i></i>目标文件 </el-divider>

    <el-form
      ref="form"
      :model="dataTarget"
      label-width="160px"
      :rules="formRules"
    >
      <el-form-item label="文件服务器类型" prop="fileserverType">
        <el-select
          v-model="dataTarget.fileserverType"
          clearable
          placeholder="请选择"
          style="width: 220px"
          @change="chooseTypeEvent()"
        >
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择目标数据源" prop="database">
        <el-select
          v-model="dataTarget.database"
          clearable
          placeholder="请选择"
          style="width: 220px"
        >
          <el-option
            v-for="item in databaseOptions"
            :key="item.id"
            :label="item.datasourceName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文件路径" prop="fileUrl">
        <el-input
          v-model="dataTarget.fileUrl"
          style="width: 220px"
          placeholder="请输入"
        ></el-input>
        <el-button
          size="small"
          type="primary"
          style="margin-left: 15px"
          @click="handleBrowsingFiles"
          >浏览文件</el-button
        >
      </el-form-item>
      <el-divider content-position="left"> <i></i>文件命名 </el-divider>
      <el-form-item label="命名规则" prop="nameRules" class="nameRules">
        <el-radio-group v-model="dataTarget.nameRules">
          <el-radio :label="1">与源文件保持一致</el-radio>
          <el-radio :label="2">
            文件名添加前缀
            <el-input
              v-show="dataTarget.nameRules == 2"
              v-model="dataTarget.namingScheme"
              style="width: 220px"
              placeholder="请输入内容"
            ></el-input>
          </el-radio>
          <el-radio :label="3">
            文件名添加后缀
            <el-input
              v-show="dataTarget.nameRules == 3"
              v-model="dataTarget.namingScheme"
              style="width: 220px"
              placeholder="请输入内容"
            ></el-input>
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-divider content-position="left"> <i></i>更新方式 </el-divider>
      <el-form-item label="更新方式" prop="updateMethods">
        <el-radio-group v-model="dataTarget.updateMethods">
          <el-radio :label="1">数据覆盖</el-radio>
          <el-radio :label="2">增量更新</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
// import { typeGetDataSource } from "@/api/dataset/database.js";
import { getColumnsType } from "@/api/dataset/table.js"
import { typeGetDataSource } from "@/api/dataset/fileserver.js"
import { browsingFiles } from "@/api/task/fileserver.js"
// import columnLinkSetting from "./columnLink";

export default {
  // components: { columnLinkSetting },
  data () {
    return {
      dialogTableVisible: false,
      formRules: {
      },
      dataTarget: {},
      // 数据库类型字典
      typeOptions: [
        {
          label: "ftp",
          value: "ftp"
        },
        {
          label: "sftp",
          value: "sftp"
        }
      ],
      updateWayOptions: [
        {
          label: "数据追加",
          value: 0
        },
        {
          label: "数据覆盖",
          value: 1
        },
        {
          label: "增量更新",
          value: 2
        }
      ],
      buildTableWayOptions: [
        {
          label: "选择已有数据表",
          value: 0
        },
        {
          label: "自动创建数据表",
          value: 1
        }
      ],
      databaseOptions: [],
      tableOptions: [], // 表数据
      tableSourceData: [], // 表下拉选择数据（标准模板数据）
      tableData: [], // 数据库表数据
      currentColumnData: [], // 当前目标表字段
      readAndWriteData: [], // 当前字段读写数据
      linkVisible: false, // 字段映射弹出框
      updateVisible: false, // 增量更新设置
      formColumnUpdate: [],
      indexUpdate: 0,
      initDataUpdate: {},
      gridData: [], // tree Node
      defaultProps: {
        children: "children",
        label: "label"
      }
    }
  },
  props: {
    initData: Object,
    mode: String,
    dataSource: Object
  },
  watch: {
    dataTarget: {
      deep: true,
      handler: function (val) {
        console.log("dataTarget", val)
        if (val.nameRules === 1) {
          val.namingScheme = ""
        }
        this.$emit("input", val)
      }
    },
    initData: {
      deep: true,
      handler: function (val) {
        // this.$refs.form.resetFields();
        this.dataTarget = {
          fileserverType: val.writerDatasourceType,
          database: val.writerDatasourceId,
          fileUrl: !val.writerFilePath ? "/" : val.writerFilePath,
          nameRules: val.namingSchemeId,
          namingScheme: val.namingScheme,
          updateMethods: val.updataWay
        }
        this.chooseTypeEvent()
        // this.dataTarget.database = val.writerDatasourceId
        let _this = this
        setTimeout(function () {
          _this.$refs.form.clearValidate()// 消除校验,这里的setTimeOut不能去掉,去掉之后会不生效
        }, 30)
      }
    }
  },
  methods: {
    //  确定选择文件
    handleconfirm () {
      console.log(this.NodeClickData)
      if (this.NodeClickData.type === 2) {
        let arr = []
        this.NodeClickData.children.forEach((item) => {
          arr.push(item.label)
        })
        let fullFile = arr.join("/")
        console.log(fullFile)
        this.dataSource.fileName = fullFile
        this.dataTarget.fileUrl += `/${this.NodeClickData.label}`
      } else {
        this.dataSource.fileName = this.NodeClickData.label
      }
      this.dialogTableVisible = false
    },
    // 返回上一级文件
    handlePrevious () {
      this.dataSource.fileName = ""
      const result = this.dataTarget.fileUrl.split("/")
      console.log(result)
      if (result.length === 2) {
        this.dataTarget.fileUrl = "/"
      } else {
        result.pop()
        const string = result.join("/")
        this.dataTarget.fileUrl = string
      }
      this.handleInitFileList()
      console.log(this.gridData)
    },
    //  初始化文件列表
    async handleInitFileList () {
      let obj = {
        readerDatasourceId: this.dataTarget.database,
        readFilePath: this.dataTarget.fileUrl
      }
      await browsingFiles(obj).then((res) => {
        let data = res.data
        // console.log(res, "查询目录返回的下级目录")
        if (data.code === 200) {
          let gridDataArr = []
          data.content.forEach((item, index) => {
            gridDataArr.push({
              label: item.fileName,
              index: index,
              path: this.dataTarget.fileUrl,
              type: item.type,
              children: []
            })
          })
          this.gridData = gridDataArr
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          })
        }
      })
    },
    handleNodeClick (data) {
      // 点击曾经请求过得路径
      this.dataTarget.fileUrl = data.path
      this.NodeClickData = data

      if (data.children.length > 0 || data.type !== 2) {
        return
      }
      this.handleBrowsingFiles(data)
    },
    handleCloseDialog () {
      this.gridData = []
    },
    async handleBrowsingFiles (clickdata) {
      if (this.dataSource.database === "") {
        this.$message({
          message: "请先选择数据源",
          type: "error"
        })
        return
      }
      if (!this.dataTarget.fileUrl) {
        this.$message({
          message: "请输入文件路径",
          type: "error"
        })
        return
      }
      this.dialogTableVisible = true
      console.log(clickdata, "点击的数据是这个")
      let obj = {
        readerDatasourceId: this.dataTarget.database,
        readFilePath: clickdata.label ? clickdata.path + `${this.dataTarget.fileUrl === "/" ? "" : "/"}` + clickdata.label : this.dataTarget.fileUrl
      }
      console.log(obj)
      await browsingFiles(obj).then((res) => {
        let data = res.data
        // console.log(res, "查询目录返回的下级目录")
        if (data.code === 200) {
          this.dialogTableVisible = true
          // 首次进入dialog渲染最外层tree
          if (!clickdata.label) {
            data.content.forEach((item, index) => {
              this.gridData.push({
                label: item.fileName,
                path: `${this.dataTarget.fileUrl}`,
                type: item.type,
                children: []
              })
            })
          } else {
            // 非首次进入dialog渲染最外层tree
            data.content.forEach((item, index) => {
              clickdata.children.push({
                label: item.fileName,
                path: `${this.dataTarget.fileUrl === "/" ? "" : this.dataTarget.fileUrl}/${clickdata.label}`,
                type: item.type,
                children: []
              })
            })
          }
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          })
        }
      })
      console.log(this.gridData)
    },
    chooseTypeEvent () {
      if (!this.dataTarget.fileserverType) { return }
      let obj = {
        type: this.dataTarget.fileserverType
      }
      typeGetDataSource(obj).then((res) => {
        let data = res.data
        if (data.code === 200) {
          this.databaseOptions = data.content
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          })
        }
      })
    },
    // 校验数据
    validateForm () {
      let flag = true

      this.$refs.form.validate((valid) => {
        if (valid) {
          flag = true
        } else {
          flag = false
          return flag
        }
      })

      if (!this.dataTarget.fileserverType || !this.dataTarget.database || !this.dataTarget.fileUrl || !this.dataTarget.updateMethods) {
        flag = false
        this.$message({
          message: "目标数据源不能为空",
          type: "error"
        })
        return flag
      }

      return flag
    },
    chooseTableEvent (row) {
      let _this = this
      let obj = {
        datasourceId: this.dataTarget.database,
        tableName: row.writerTable
      }
      getColumnsType(obj).then((res) => {
        let data = res.data
        if (data.code === 200) {
          this.currentColumnData = data.content
          _this.dataTarget.writeToDataSources.forEach(x => {
            if (x.datasourceId === row.datasourceId) {
              _this.$set(x, "writerColumns", data.content)
            }
          })
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          })
        }
      })
    },
    setLinkEvent (row) {
      // console.log("row", row);
      this.readAndWriteData = row
      this.linkVisible = true
    },
    setUpdateEvent (row, index) {
      this.indexUpdate = index
      this.updateVisible = true
      this.initDataUpdate = row

      let _options = []
      if (row.requestParams) {
        row.requestParams.map(x => {
          let obj = {
            label: x.paramName,
            value: x.paramName
          }
          _options.push(obj)
        })
      }
      this.formColumnUpdate = [
        {
          name: "startTimeParamName",
          label: "增量更新开始时间",
          type: "select",
          multiple: false,
          options: _options
        },
        {
          name: "endTimeParamName",
          label: "增量更新结束时间",
          type: "select",
          multiple: false,
          options: _options
        }
      ]
    }
  },
  mounted () {
    // this.initFormColumn();
    // if (this.initData.writerColumns) { this.initSelection = [...this.initData.writerColumns]; }
    // this.setRules();
    this.formRules = {
      fileserverType: [{ required: true, message: "不能为空" }],
      database: [{ required: true, message: "不能为空" }],
      fileUrl: [{ required: true, message: "不能为空" }],
      updateMethods: [{ required: true, message: "不能为空" }]
    }
  }
};
</script>
<style lang="scss" scoped>
/deep/ .nameRules .el-radio {
  display: block;
  line-height: 2em;
  white-space: normal;
  margin-right: 0;
}
.dataTarget {
  .el-divider__text.is-left {
    left: 0;
    display: flex;
    flex-direction: row;
    > i {
      display: block;
      width: 3px;
      height: 14px;
      background: #128df3;
      margin-right: 5px;
    }
  }
  .tableBox {
    padding-left: 40px;
  }
}
</style>
